<template>
  <div class="page">
    <s-header :name="'竣工申请'" :back="'/home'"></s-header>
    <van-form ref="dataForm" class="start-apply">
      <div class="card-box">
        <div class="card-item">
          <div class="card-header">申请选择</div>
          <van-divider />
          <div class="card-body card-body-nop">
            <custom-select
              :selectId="applyBaseId"
              :columns="buildApplyColumns"
              :otherOrg="otherOrg"
              :option="{ label: 'applyOrderNo', value: 'id' }"
              :rules="dataRule.applyBaseId"
              :disabled="disabledSelect"
              required
              label="建房申请记录"
              label-width="100px"
              @getValue="getValue"
            ></custom-select>
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header title-required">申请内容</div>
          <van-divider />
          <div class="card-body">
            <van-field
              v-model="applyContent"
              :rules="dataRule.applyContent"
              rows="3"
              autosize
              label=""
              type="textarea"
              maxlength="100"
              placeholder=""
              show-word-limit
              class="noPadding"
            />
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header title-required">现场图片</div>
          <van-divider />
          <div class="card-body">
            <image-upload v-model:value="pictures" fileType="A18" @uploadBack="uploadBack"></image-upload>
          </div>
        </div>
      </div>
      <div class="card-box">
        <div class="card-item">
          <div class="card-header">相关材料</div>
          <van-divider style="margin-bottom: 10px" />
          <div class="card-body">
            <image-upload
              v-model:value="providedMaterials"
              :maxCount="10"
              fileType="A19"
              @uploadBack="uploadBack"
            ></image-upload>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <van-button :loading="isCommit" type="button" class="cus-btn btn-default" @click="handleSave">保存</van-button>
        <van-button :loading="isCommit" type="button" class="cus-btn btn-primary" @click="handleSubmit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onBeforeMount, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Toast } from 'vant'
import ImageUpload from '@/components/ImageUpload'
import sHeader from '@/components/SimpleHeader'
import { saveBuildCompletedApply, getFinishBuildApplyNotice } from '@/service/start-apply'
import { getFinishApplyDetail } from '@/service/home'
export default {
  components: {
    sHeader,
    ImageUpload,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const dataForm = ref(null)
    const state = reactive({
      isCommit: false,
      fileList: [],
      applyBaseId: null,
      finishId: '',
      otherOrg: ['applyName', 'applyTime'],
      disabledSelect: false,
      applyContent: '',
      buildApplyColumns: [],
      pictures: [],
      providedMaterials: [],
      otherMaterials: [],
      attachInfoOtherList: [],
      attachInfoPhotoList: [],
      dataRule: {
        applyBaseId: [{ required: true, message: '请选择建房申请记录', trigger: 'onChange' }],
        applyContent: [{ required: true, message: '请输入申请内容', trigger: 'onBlur' }],
      },
    })

    // 获取建房申请记录
    getFinishBuildApplyNotice().then((res) => {
      state.buildApplyColumns = res.body.obj || []
    })
    store.dispatch('getFileServerPrefix')

    onBeforeMount(async () => {
      const { id } = route.query
      if (id) {
        getFinishApplyDetail(id).then((res) => {
          const buildCompletedApply = res.data.buildCompletedApply
          if (buildCompletedApply) {
            const { id, applyOrderNo, applyName, applyTime } = res.data.buildApplyBase
            state.buildApplyColumns.push({
              id: id,
              applyOrderNo: applyOrderNo,
              applyName: applyName,
              applyTime: applyTime,
            })
            state.disabledSelect = true
          }

          let files = buildCompletedApply.files
          let photos = buildCompletedApply.photos
          if (files && files.length > 0) {
            files.forEach((item) => {
              item.filePath = item.url
              item.url = fileServerPrefix.value + item.url
            })
          }
          if (photos && photos.length > 0) {
            photos.forEach((item) => {
              item.filePath = item.url
              item.url = fileServerPrefix.value + item.url
            })
          }
          state.finishId = buildCompletedApply.id
          state.applyBaseId = buildCompletedApply.applyBaseId
          state.applyContent = buildCompletedApply.applyContent
          state.pictures = photos
          state.providedMaterials = files
        })
      }
    })

    // 文件上传后回调
    const uploadBack = (fileList, type) => {
      if (type === 'A18') {
        state.pictures = fileList
      } else if (type === 'A19') {
        state.providedMaterials = fileList
      }
    }

    // 获取建房申请记录id
    const getValue = (val) => {
      state.applyBaseId = val
    }

    const handSendData = (isSubmit) => {
       return new Promise((resove, reject) => {
        let pictures = JSON.parse(JSON.stringify(state.pictures))
        let providedMaterials = JSON.parse(JSON.stringify(state.providedMaterials))
        pictures.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        providedMaterials.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })

        let params = {
          applyBaseId: state.applyBaseId,
          applyContent: state.applyContent,
          attachInfoPhotoList: pictures,
          attachInfoOtherList: providedMaterials,
          isSubmit: isSubmit,
          id: state.finishId,
        }
        state.isCommit = true
        saveBuildCompletedApply(params)
          .then(() => {
            resove(true)
            state.isCommit = false
          })
          .catch((err) => {
            state.isCommit = false
            reject(err)
          })
      })
    }

    // 保存
    const handleSave = () => {
      if (state.applyBaseId) {
        handSendData(false).then(() => {
          Toast.success('保存成功')
          setTimeout(() => {
            router.push({ path: '/record-apply/record-list', query: { applyType: 3 } })
          }, 500)
        })
      } else {
        Toast.fail('请选择建房申请记录')
      }
    }
    // 提交数据
    const handleSubmit = () => {
      dataForm.value.validate().then(() => {
        if (!state.pictures || state.pictures.length === 0) {
          Toast.fail(`请上传现场图片`)
          return
        }
        // 非必填
        // if (!state.attachInfoOtherList || state.attachInfoOtherList.length === 0) {
        //   Toast.fail(`应提供材料`)
        //   return
        // }

        handSendData(true).then(() => {
          Toast.success('提交成功')
          setTimeout(() => {
            router.push({
              name: 'ResultsPage',
              params: {
                stepList: JSON.stringify([
                  { title: '竣工申请提交成功', desc: '您已成功提交竣工申请，请等待相关部门现场验收。', finishTime: '' },
                  { title: '等待审批通知', desc: '验收通过后，领取乡镇政府出具的《农村宅基地和建房（规划许可）验收意见》', finishTime: '' },
                ]),
                stepActive: 1,
                applyType: 3,
              },
            })
          }, 500)
        })
      })
    }

    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    return {
      dataForm,
      fileServerPrefix,
      ...toRefs(state),
      handleSave,
      handleSubmit,
      getValue,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.start-apply {
  padding-top: 12px;
  .title-required::before {
    margin-right: 5px;
    color: var(--van-field-required-mark-color);
    content: '*';
  }
  .card-body {
    .file-title {
      font-size: 15px;
      font-weight: 400;
      color: #2e3f6a;
      margin-bottom: 5px;
    }
    .file-title:nth-child(5) {
      margin-bottom: 10px;
    }
    // .craftsman-group {
    //   padding: 8px 14px 13px;
    // }
  }
  .btn-group {
    padding: 20px 0;
    .cus-btn {
      width: 167px;
    }
  }
}
</style>
